<template>
  <div class="page-miH page-bgBack">
    <PageHeader @back="$router.go(-1)" subTitle="返回"> </PageHeader>
    <div class="add-payslip">
      <a-spin :spinning="spinning">
        <a-row class="content-con">
          <h2 class="title"><a-icon type="file-text" theme="filled" class="mr4" style="color: var(--primary)" />上传派单表</h2>
          <a-form class="form" :form="form" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-row>
              <a-form-item class="form-item" label="派单任务名称">
                <a-input v-model="TaskName" placeholder="请输入" style="width: 300px" />
              </a-form-item>
            </a-row>
            <a-row>
              <a-form-item label="选择模式">
                <SelectWithInputAdd v-model="tableName" editable allowClear dictCode="1204" placeholder="请选择模式" style="width: 300px" />
              </a-form-item>
            </a-row>
            <a-row>
              <a-form-item class="form-item" label="选择月份">
                <a-month-picker v-model="selectDate" format="YYYY-MM" style="width: 300px" placeholder="请选择" />
              </a-form-item>
            </a-row>
            <a-row>
              <a-form-item class="form-item" label="选择派单对象">
                <a-radio-group name="radioGroup" v-model="comtype" @change="onRadioChange">
                  <a-radio :value="1"> 固定用工单位 </a-radio>
                  <a-radio :value="2"> 固定业务员 </a-radio>
                </a-radio-group>
              </a-form-item>
            </a-row>
            <a-row>
              <a-form-item class="form-item" label="派单单位/业务员">
                <a-tree-select
                  v-if="comtype === 1"
                  v-model="companyList"
                  :treeData="companyTreeWithUuid"
                  :replaceFields="replaceFields2"
                  labelInValue
                  showSearch
                  treeNodeFilterProp="title"
                  placeholder="请选择用工单位"
                  tree-checkable
                  style="width: 300px"
                />
                <a-select
                  v-if="comtype === 2"
                  v-model="selectCompanyId"
                  labelInValue
                  mode="multiple"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  placeholder="请选择业务员"
                  style="width: 300px"
                >
                  <a-select-option v-for="i in dataSource" :key="i.id">
                    {{ i.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-row>
            <a-form-item label="选择图片/表单" class="form-item">
              <a-radio-group v-model="uploadType">
                <a-radio value="1">上传图片</a-radio>
                <a-radio value="2">导入表单</a-radio>
              </a-radio-group>
            </a-form-item>
            <template v-if="uploadType === '1'">
              <a-form-item v-show="uploadType === '1'" label="上传图片" class="form-item">
                <UploadGeneralInline :limit="10" @change="onImgChange" @loading="onUploadLoading" />
              </a-form-item>
              <div class="ta-center mt24 ml48">
                <a-button type="primary" :disabled="disabledBtn" @click="doUploadImgs">提交</a-button>
              </div>
            </template>
            <a-form-item v-if="uploadType === '2'" label="选择派单表" class="form-item">
              <a-upload :show-upload-list="false" :action="action" :custom-request="beforeUpload">
                <a-button ref="onUpload" style="width: 300px" type="primary" :disabled="disabled" @click="onUpload">导入派单表</a-button>
                <a-spin v-if="spining" style="margin-left: 15px" />
              </a-upload>
            </a-form-item>
          </a-form>
        </a-row>
        <a-row v-show="uploadType === '2'" class="content-foot">
          <div style="font-size: 16px; font-weight: 500; color: #55565d">导入说明</div>
          <div class="sub_tit" style="margin-top: 10px">1、导入模板前两列必须为姓名、身份证号</div>
          <div class="sub_tit" style="margin-top: 10px">2、不支持合并单元格上传</div>
        </a-row>
      </a-spin>
      <!-- 弹窗 -->
      <a-modal title="错误信息" :visible="showModal" @ok="sureImport" @cancel="$router.go(-1)">
        <a-row v-for="(item, i) in wrongList" :key="i"> 第 {{ item.row }} 行 : {{ item.msgList }}</a-row>
      </a-modal>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { userList } from "@/api/company/member";
import { getToken } from "xqjr-module-auth";
import moment from "moment";
import axios from "axios";
import SelectWithInputAdd from "xqjr-plugin-form/components/XqSelectWithInputAdd.vue";
import UploadGeneralInline from "xqjr-plugin-common/FileHandler/UploadGeneralInline.vue";
export default {
  name: "AddPayslip",
  components: { SelectWithInputAdd, UploadGeneralInline },
  data() {
    return {
      imgLst: "",
      uploadType: "2",
      spining: false,
      moment,
      companyList: [],
      replaceFields2: {
        children: "companyList",
        title: "name",
        key: "uuid",
        value: "uuid"
      },
      urlList: [],
      comtype: 1,
      yewuList: [],
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
      selectCompanyId: [],
      showModal: false,
      wrongList: [],
      formData: null,
      addOrLess: true,
      selectDate: undefined,
      tableName: undefined,
      TaskName: undefined,
      action: "",
      dataSource: [],
      excelVisible: false,
      excelOptions: {},
      titles: {},
      cbParams: {
        pageNo: 1,
        reloadCount: true,
        pageSize: 10
      },
      pagination: {
        pageSize: 10,
        current: 1,
        total: 0
      },
      salary: [],
      hide: false,
      fileName: "",
      form: this.$form.createForm(this, { name: "coordinated" }),
      tableId: "",
      hasMonth: [],
      spinning: false
    };
  },
  computed: {
    ...mapState(["hr", "site"]),
    disabled() {
      return !(
        this.TaskName &&
        this.tableName &&
        this.selectDate !== undefined &&
        (this.companyList.length > 0 || this.selectCompanyId.length > 0)
      );
    },
    disabledBtn() {
      if (this.TaskName && this.tableName && this.selectDate !== undefined) {
        if ((this.comtype === 1 && this.companyList.length > 0) || (this.comtype === 2 && this.selectCompanyId.length > 0)) {
          if (this.imgLst) {
            return false;
          }
        }
      }
      return true;
    },
    companyTreeWithUuid() {
      return this.site.companyTreeWithUuid;
    },
    companyUuidDict() {
      return this.site.companyUuidDict;
    }
  },
  watch: {
    companyTreeWithUuid: {
      handler(newVal) {
        if (newVal.length > 0) {
          this.companyList = JSON.parse(JSON.stringify(this.companyList));
        }
      },
      immediate: true
    }
  },
  created() {
    if (this.$route.query.pageState && this.$route.query.pageState === "2") {
      this.TaskName = sessionStorage.getItem("TaskName") ? sessionStorage.getItem("TaskName") : undefined;
      this.tableName = sessionStorage.getItem("tableName") ? sessionStorage.getItem("tableName") : undefined;
      this.selectDate = sessionStorage.getItem("selectDate") ? sessionStorage.getItem("selectDate") : undefined;
      this.comtype = sessionStorage.getItem("comtype") ? parseInt(sessionStorage.getItem("comtype")) : 1;
      this.companyList = sessionStorage.getItem("companyList") ? JSON.parse(sessionStorage.getItem("companyList")) : [];
      this.selectCompanyId = sessionStorage.getItem("selectCompanyId") ? JSON.parse(sessionStorage.getItem("selectCompanyId")) : [];
    }
    this.headers = {
      token: getToken(),
      "Content-Type": "multipart/form-data"
    };
    this.gethasCanBaoMonth();
    this.getUserRolesList();
  },

  methods: {
    onUploadLoading(val) {
      this.spinning = val;
    },
    onImgChange(res) {
      this.imgLst = res;
    },
    doUploadImgs() {
      this.$request({
        url: `/hr/api/v1/missionCenters`,
        method: "post",
        data: {
          subjectId: (this.comtype === 1
            ? this.companyList.map((item) => this.companyUuidDict[item.value])
            : this.selectCompanyId.map((item) => item.key)
          ).join(","),
          subjectType: this.comtype,
          state: 0,
          missionName: this.TaskName,
          fileUrl: this.imgLst,
          fileType: 2,
          missionMode: this.tableName,
          year: moment(this.selectDate).format("YYYY"),
          month: moment(this.selectDate).format("MM")
        }
      })
        .then((res) => {
          this.$message.success("提交成功");
          this.$router.back();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    async getUserRolesList() {
      const { data } = await this.$request({ url: `/hr/api/v1/users/dispatchList` });
      this.dataSource = data;
    },
    userList() {
      userList()
        .then((res) => {
          console.log("debug log --> ", res);
          this.yewuList = res.data;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    onRadioChange(e) {
      this.companyList = [];
      this.selectCompanyId = [];
    },
    // 获取有参保的月份
    gethasCanBaoMonth() {
      this.$request({
        url: `/hr/api/v1/empSocMonths/listYearAndMonth/${this.hr.companyId}`
      }).then(({ data }) => {
        this.hasMonth = data || [];
      });
    },
    // 导入工资表
    onUpload() {
      const [year, month] = this.selectDate.format("YYYY-MM").split("-");
      this.action = this.addOrLess
        ? `/hr/api/v1/socDispatchEmpAdds/import?companyId=${this.selectCompanyId}&month=${month}&year=${year}`
        : `/hr/api/v1/socDispatchEmpLesses/import?companyId=${this.selectCompanyId}&month=${month}&year=${year}`;
    },
    // 预导入
    beforeUpload({ file }) {
      this.spining = true;
      this.fileName = [file][0].name;
      const formData = new FormData();
      const formData2 = new FormData();
      this.formData = formData;
      formData.append("file", file);
      formData2.append("files", file);
      this.$request({
        url: `/hr/api/v1/missionCenters/parseImport`,
        method: "post",
        data: formData
      })
        .then((resA) => {
          this.spining = false;
          axios({
            url: "/file/api/v1/general/upload/inline",
            method: "post",
            data: formData2,
            headers: this.headers
          })
            .then((res) => {
              this.spining = false;
              sessionStorage.setItem("TaskName", this.TaskName);
              sessionStorage.setItem("tableName", this.tableName);
              sessionStorage.setItem("selectDate", this.selectDate);
              sessionStorage.setItem("comtype", this.comtype);
              sessionStorage.setItem("companyList", JSON.stringify(this.companyList));
              sessionStorage.setItem("selectCompanyId", JSON.stringify(this.selectCompanyId));
              this.urlList = res.data.data;
              this.$router.push({
                path: "/admin/preview",
                query: {
                  head: JSON.stringify(resA.data.head),
                  list: JSON.stringify(resA.data.headDataMap),
                  urlList: this.urlList,
                  fileName: this.fileName,
                  form: JSON.stringify({
                    TaskName: this.TaskName,
                    tableName: this.tableName,
                    selectDate: moment(this.selectDate).format("YYYY-MM"),
                    comtype: this.comtype,
                    companyList: JSON.stringify(this.companyList),
                    selectCompanyId: JSON.stringify(this.selectCompanyId)
                  })
                }
              });
            })
            .catch(() => {
              this.spining = false;
            });
        })
        .catch(() => {
          this.spining = false;
        });
    },
    // 确定导入
    sureImport() {
      this.$request({
        url: this.action,
        method: "post",
        data: this.formData
      }).then(({ data, success }) => {
        if (success) {
          this.formData = null;
          this.showModal = false;
          const path = this.addOrLess ? "/shebao/shebaoPaidan/shebao-add-list" : "/shebao/shebaoPaidan/shebao-add-list-less";
          this.$router.push({
            path,
            query: { id: data.id, addOrLess: this.addOrLess }
          });
        }
      });
    },
    cbUpload(e) {
      if (e.file && e.file.response && e.file.response.data) {
        const response = e.file.response;

        if (response.success) {
          const path = this.addOrLess ? "/shebao/shebaoPaidan/shebao-add-list" : "/shebao/shebaoPaidan/shebao-add-list-less";
          this.$router.push({
            path,
            query: { id: response.data.id, addOrLess: this.addOrLess }
          });
        } else {
          this.$notification["error"]({ message: response.msg });
        }
      }
    },
    // 下载模板
    downLoad(type) {
      const url =
        type === "+"
          ? `http://hjrl-public.oss-cn-qingdao.aliyuncs.com/excel_template/emp_info/soc/%E5%A2%9E%E5%91%98%E6%A8%A1%E6%9D%BF.xlsx`
          : `http://hjrl-public.oss-cn-qingdao.aliyuncs.com/excel_template/emp_info/soc/%E5%87%8F%E5%91%98%E6%A8%A1%E6%9D%BF.xlsx`;
      var newUrl = url.replace("http", "https");
      window.open(newUrl, "_self");
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .form {
  text-align: center;
  .form-item {
    margin: 10px 0;
    text-align: left;
  }
}
.add-payslip {
  padding: 24px;
  .content-top {
    margin-top: 24px;
    padding: 40px 25%;
    background: #fafafa;
    border-radius: 4px;
  }
  .content-con {
    text-align: center;
    padding: 40px 162px 50px 132px;
    background: #ffffff;
    box-shadow: 0px 4px 12px 0px rgba(106, 102, 246, 0.2);
    border-radius: 4px;
    border-radius: 4px;
  }
  .content-foot {
    margin-top: 24px;
    padding: 24px;
    background: #fafafa;
    border-radius: 4px;
  }
  .salary {
    cursor: pointer;
    margin: 24px 0;
    .item {
      padding: 24px;
      text-align: center;
      border: 1px solid #ccc;
      border-radius: 4px;
    }
  }
}
</style>
